<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="60px">
<el-form-item prop="boxNo"><el-input v-model="queryParams.boxNo" placeholder="请输入灯杆序号" clearable size="small" @keyup.enter.native="handleQuery"/></el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button></el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
<el-col :span="1.5"><el-button type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd" v-hasPermi="['iot:hgbox:add']">新增</el-button></el-col>
<el-col :span="1.5"><el-button type="success" plain icon="el-icon-edit" size="small" :disabled="single" @click="handleUpdate" v-hasPermi="['iot:hgbox:edit']">修改</el-button></el-col>
<el-col :span="1.5"><el-button type="danger" plain icon="el-icon-delete" size="small" :disabled="multiple" @click="handleDelete" v-hasPermi="['iot:hgbox:remove']">删除</el-button></el-col>
<el-col :span="1.5"><el-button id="openbtn" type="success" :plain="selectedRows.length===0" size="mini" :disabled="selectedRows.length===0" @click="handleTurnOn(selectedRows)">
          <i class="el-icon-video-play" style="font-size: 1.3em; margin-right: 6px;"></i>开启</el-button>
<el-button id="closebtn" type="danger" :plain="selectedRows.length===0" size="mini" :disabled="selectedRows.length===0" @click="handleTurnOff(selectedRows)">
          <i class="el-icon-video-pause" style="font-size:1.3em;margin-right:6px;"></i>关闭</el-button></el-col>
<el-col :span="2.1" style="margin-left:5px;display:flex;align-items:center;"><span style="font-size:12px;margin-right:5px;">亮度</span>
          <el-select v-model="sldLightLvl" :disabled="selectedRows.length===0" size="mini" style="width:100px;" @change="updtLevel">
              <el-option v-for="option in ooptions" :key="option" :label="option" :value="option"/></el-select></el-col>
<el-col :span="1.5"><el-button type="primary" plain icon="el-icon-time" size="small" @click="openDialog" :disabled="selectedRows.length===0" :class="{'plain-button':selectedRows.length===0}">定时</el-button></el-col>
    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar></el-row>
    <el-table v-loading="loading" :data="hgboxList" style="width:100%" border @selection-change="handleSelectionChange" fit @mouseenter.native="handleTableMouseEnter" @mouseleave.native="handleTableMouseLeave" ref="dataTable" class="hover-operate-table">
      <el-table-column type="selection" width="45" align="center"/>
      <el-table-column label="ID" align="center" prop="id" v-if="false"/>
      <el-table-column label="客户" align="center" prop="adminNickname" width="155" show-overflow-tooltip/>
      <el-table-column label="项目" align="center" prop="faProject.projectname" width="155" show-overflow-tooltip/>
      <el-table-column label="灯杆名称" align="center" prop="lightName" width="155" show-overflow-tooltip/>
      <el-table-column label="灯杆序号" align="center" prop="boxNo" show-overflow-tooltip/>
      <el-table-column label="在线状态" align="center" width="86">
<template slot-scope="scope"><div class="status-container"><img :src="getStateImags(scope.row.state)" alt="在线状态" style="width:22px;height:22px;"/></div></template>
      </el-table-column>
      <el-table-column label="工作状态" align="center">
<template slot-scope="scope"><div class="status-container"><img :src="getStatusImage(scope.row.lightStatus)" alt="工作状态" style="width:22px;height:22px;"/></div></template>
      </el-table-column>
      <el-table-column label="灯控类型" prop="provideType" align="center" width="80">
<template slot-scope="scope"><dict-tag :options="dict.type.iot_provide_type" :value="scope.row.provideType"/></template>
      </el-table-column>
      <el-table-column label="监控设备号" align="center" width="125" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.ysNoun">{{scope.row.ysNoun}}</span>
          <span v-else style="color:#f56c6c;font-weight:bold;background-color:#fff4f4;padding:2px 6px;border-radius:4px;font-size:14px;">未配置</span>
        </template>
      </el-table-column>
      <el-table-column label="调光等级" align="center" prop="lightAdjustLevel" />
      <el-table-column label="电流" align="center" prop="lightCurrent" />
      <el-table-column label="电压" align="center" prop="lightVolt" />
      <el-table-column label="功率" align="center" prop="activePower" />
      <el-table-column label="信号强度" align="center" prop="signalt" />
      <el-table-column label="故障报警" align="center">
<template slot-scope="scope"><div class="status-container"><img :src="getLampErrorImage(scope.row.lampError)" alt="故障报警" style="width:33px;height:33px;"/></div></template>
      </el-table-column>
      <el-table-column label="定时策略" align="center" prop="content">
        <template slot-scope="scope">
          <img v-if="cronBoxNoList.includes(scope.row.boxNo)" :src="require(`@/assets/bigScreen/img/localStrategy.png`)"
            style="width:18px;height:auto;cursor:pointer;" @click="openStrategyDialog(scope.row)" v-hasPermi="['iot:cron:edit']"/>
  <span v-else style="color:#f56c6c;font-weight:bold;background-color:#fff4f4;padding:2px 6px;border-radius:4px;font-size:14px;">未定时</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="157">
        <template slot-scope="scope">{{scope.row.createTime}}</template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="157">
        <template slot-scope="scope">{{scope.row.updateTime||'未更新'}}</template>
      </el-table-column>
      <el-table-column label="能耗趋势" align="center">
        <template slot-scope="scope">
          <el-popover placement="right" width="500" trigger="click">
            <div class="energy-consumption-chart">
              <div class="time-range-selector">
                <el-radio-group v-model="energyTimeRange" size="mini" @change="fetchEnergyData(scope.row)">
                  <el-radio-button label="day">日</el-radio-button>
                  <el-radio-button label="month">月</el-radio-button>
                  <el-radio-button label="year">年</el-radio-button>
                </el-radio-group>
              </div>
              <div class="chart-container" ref="energyChart" style="width:100%;height:300px;"></div>
            </div>
            <el-button slot="reference" type="text" icon="el-icon-data-line" style="font-size:22px;"/>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="280" :class-name="showOperateColumn?'operate-column show':'operate-column'">
        <template slot-scope="scope">
  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['iot:hgbox:edit']">修改</el-button>
  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['iot:hgbox:remove']">删除</el-button>
  <el-button size="mini" type="text" icon="el-icon-message" @click="operateUp(scope.row)" v-hasPermi="['iot:log:list']">操作记录</el-button>
  <el-button size="mini" type="text" icon="el-icon-time" @click="historyUpd(scope.row)" v-hasPermi="['iot:hgbox:history']">历史记录</el-button>
        </template>
      </el-table-column>
    </el-table>
<pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" :page-sizes="pageSizes" @pagination="getList"/>
<pelect-uusser ref="select"/>
<history-uusser ref="history"/>
<el-dialog title="定时设置" :visible.sync="dialogVisible" width="30%">
<el-form :model="form">
<el-row :gutter="30" style="margin-left:3px;"><span style="font-size:16px;color:#4169E1;">策略1</span></el-row>
<el-row :gutter="20" style="margin-left:50px;margin-top:-26px;">
<el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.startTime" placeholder="开启时间" field="startTime"/></el-form-item></el-col>
<el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.endTime" placeholder="关闭时间" field="endTime"/></el-form-item></el-col></el-row>
        <div><el-select v-model="form.lightAdjustLevel" placeholder="调光等级" class="custom-select move-select">
            <el-option label="0%" value="0%"/>
            <el-option label="10%" value="10%"/>
            <el-option label="20%" value="20%"/>
            <el-option label="30%" value="30%"/>
            <el-option label="40%" value="40%"/>
            <el-option label="50%" value="50%"/>
            <el-option label="60%" value="60%"/>
            <el-option label="80%" value="80%"/>
            <el-option label="100%" value="100%"/></el-select></div>
        <el-row :gutter="30" style="margin-left:3px;"><span style="font-size:16px;color:#4169E1;">策略2</span></el-row>
        <el-row :gutter="20" style="margin-left: 50px; margin-top:-26px;">
          <el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.startTimeTwo" field="startTimeTwo" placeholder="开启时间"/></el-form-item></el-col>
          <el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.endTimeTwo" field="endTimeTwo" placeholder="关闭时间"/></el-form-item></el-col></el-row>
        <div><el-select v-model="form.lightAdjustLevelTwo" placeholder="调光等级" class="custom-select move-select">
            <el-option label="0%" value="0%"/>
            <el-option label="10%" value="10%"/>
            <el-option label="20%" value="20%"/>
            <el-option label="30%" value="30%"/>
            <el-option label="40%" value="40%"/>
            <el-option label="50%" value="50%"/>
            <el-option label="60%" value="60%"/>
            <el-option label="80%" value="80%"/>
            <el-option label="100%" value="100%"/></el-select></div>
        <el-row :gutter="30" style="margin-left:3px;"><span style="font-size:16px;color:#4169E1;">策略3</span></el-row>
        <el-row :gutter="20" style="margin-left:50px;margin-top:-26px;">
          <el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.startTimeThree" field="startTimeThree" placeholder="开启时间"/></el-form-item></el-col>
          <el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.endTimeThree" field="endTimeThree" placeholder="关闭时间"/></el-form-item></el-col></el-row>
        <div><el-select v-model="form.lightAdjustLevelThree" placeholder="调光等级" class="custom-select move-select">
            <el-option label="0%" value="0%"/>
            <el-option label="10%" value="10%"/>
            <el-option label="20%" value="20%"/>
            <el-option label="30%" value="30%"/>
            <el-option label="40%" value="40%"/>
            <el-option label="50%" value="50%"/>
            <el-option label="60%" value="60%"/>
            <el-option label="80%" value="80%"/>
            <el-option label="100%" value="100%"/></el-select></div>
        <el-row :gutter="30" style="margin-left:3px;"><span style="font-size:16px;color:#4169E1;">策略4</span></el-row>
        <el-row :gutter="20" style="margin-left:50px;margin-top:-26px;">
          <el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.startTimeFour" field="startTimeFour" placeholder="开启时间"/></el-form-item></el-col>
          <el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.endTimeFour" field="endTimeFour" placeholder="关闭时间"/></el-form-item></el-col></el-row>
        <div><el-select v-model="form.lightAdjustLevelFour" placeholder="调光等级" class="custom-select move-select">
            <el-option label="0%" value="0%"/>
            <el-option label="10%" value="10%"/>
            <el-option label="20%" value="20%"/>
            <el-option label="30%" value="30%"/>
            <el-option label="40%" value="40%"/>
            <el-option label="50%" value="50%"/>
            <el-option label="60%" value="60%"/>
            <el-option label="80%" value="80%"/>
            <el-option label="100%" value="100%"/></el-select></div>
        <el-row :gutter="30" style="margin-left:3px;"><span style="font-size:16px;color:#4169E1;">策略5</span></el-row>
        <el-row :gutter="20" style="margin-left:50px;margin-top:-26px;">
          <el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.startTimeFive" field="startTimeFive" placeholder="开启时间"/></el-form-item></el-col>
          <el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
        <time-picker v-model="form.endTimeFive" field="endTimeFive" placeholder="关闭时间"/></el-form-item></el-col></el-row>
        <div><el-select v-model="form.lightAdjustLevelFive" placeholder="调光等级" class="custom-select move-select">
            <el-option label="0%" value="0%"/>
            <el-option label="10%" value="10%"/>
            <el-option label="20%" value="20%"/>
            <el-option label="30%" value="30%"/>
            <el-option label="40%" value="40%"/>
            <el-option label="50%" value="50%"/>
            <el-option label="60%" value="60%"/>
            <el-option label="80%" value="80%"/>
            <el-option label="100%" value="100%"/></el-select></div></el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmitForStrategys">确 定</el-button></span>
    </el-dialog>
    <el-dialog title="定时策略详情" :visible.sync="dialogVisibleForStrategy" width="30%">
        <el-form ref="form" :model="form" label-width="58px">
          <el-form-item label="灯杆号:" prop="boxNo"><span style="font-size:16px;">{{this.form.boxNo}}</span></el-form-item>
          <el-row :gutter="30" style="margin-left:3px;"><span style="font-size:16px;color:#4169E1;">策略1</span></el-row>
          <el-row :gutter="10" style="margin-left:-3px;margin-top:-26px;">
<el-col :span="10"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.startTime" field="startTime" placeholder="开启时间" @change="handleEndTimeChange"/></el-form-item></el-col>
<el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.endTime" field="endTime" placeholder="关闭时间" @change="handleEndTimeChange"/></el-form-item></el-col></el-row>
          <div><el-select v-model="form.lightAdjustLevel" placeholder="调光等级" class="custom-select move-select" @change="handlelightAdjustLevel">
              <el-option label="0%" value="0%"/>
              <el-option label="10%" value="10%"/>
              <el-option label="20%" value="20%"/>
              <el-option label="30%" value="30%"/>
              <el-option label="40%" value="40%"/>
              <el-option label="50%" value="50%"/>
              <el-option label="60%" value="60%"/>
              <el-option label="80%" value="80%"/>
              <el-option label="100%" value="100%"/></el-select></div>
          <el-row :gutter="30" style="margin-left:3px;"><span style="font-size:16px;color:#4169E1;">策略2</span></el-row>
          <el-row :gutter="10" style="margin-left:-3px;margin-top:-26px;">
<el-col :span="10"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.startTimeTwo" field="startTimeTwo" placeholder="开启时间" @change="handleEndTimeChange"/></el-form-item></el-col>
<el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.endTimeTwo" field="endTimeTwo" placeholder="关闭时间" @change="handleEndTimeChange"/></el-form-item></el-col></el-row>
          <div><el-select v-model="form.lightAdjustLevelTwo" placeholder="调光等级" class="custom-select move-select" @change="handlelightAdjustLevelTwo">
              <el-option label="0%" value="0%"/>
              <el-option label="10%" value="10%"/>
              <el-option label="20%" value="20%"/>
              <el-option label="30%" value="30%"/>
              <el-option label="40%" value="40%"/>
              <el-option label="50%" value="50%"/>
              <el-option label="60%" value="60%"/>
              <el-option label="80%" value="80%"/>
              <el-option label="100%" value="100%"/></el-select></div>
        <el-row :gutter="30" style="margin-left:3px;"><span style="font-size:16px;color:#4169E1;">策略3</span></el-row>
        <el-row :gutter="10" style="margin-left:-3px;margin-top:-26px;">
<el-col :span="10"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.startTimeThree" field="startTimeThree" placeholder="开启时间" @change="handleEndTimeChange"/></el-form-item></el-col>
<el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.endTimeThree" field="endTimeThree" placeholder="关闭时间" @change="handleEndTimeChange"/></el-form-item></el-col></el-row>
        <div><el-select v-model="form.lightAdjustLevelThree" placeholder="调光等级" class="custom-select move-select" @change="handlelightAdjustLevelThree">
            <el-option label="0%" value="0%"/>
            <el-option label="10%" value="10%"/>
            <el-option label="20%" value="20%"/>
            <el-option label="30%" value="30%"/>
            <el-option label="40%" value="40%"/>
            <el-option label="50%" value="50%"/>
            <el-option label="60%" value="60%"/>
            <el-option label="80%" value="80%"/>
            <el-option label="100%" value="100%"/></el-select></div>
        <el-row :gutter="30" style="margin-left:3px;"><span style="font-size:16px;color:#4169E1;">策略4</span></el-row>
        <el-row :gutter="10" style="margin-left:-3px;margin-top:-26px;">
<el-col :span="10"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.startTimeFour" field="startTimeFour" placeholder="开启时间" @change="handleEndTimeChange"/></el-form-item></el-col>
<el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.endTimeFour" field="endTimeFour" placeholder="关闭时间" @change="handleEndTimeChange"/></el-form-item></el-col></el-row>
        <div><el-select v-model="form.lightAdjustLevelFour" placeholder="调光等级" class="custom-select move-select" @change="handlelightAdjustLevelFour">
            <el-option label="0%" value="0%"/>
            <el-option label="10%" value="10%"/>
            <el-option label="20%" value="20%"/>
            <el-option label="30%" value="30%"/>
            <el-option label="40%" value="40%"/>
            <el-option label="50%" value="50%"/>
            <el-option label="60%" value="60%"/>
            <el-option label="80%" value="80%"/>
            <el-option label="100%" value="100%"/></el-select></div>
        <el-row :gutter="30" style="margin-left:3px;"><span style="font-size:16px;color:#4169E1;">策略5</span></el-row>
        <el-row :gutter="10" style="margin-left:-3px;margin-top:-26px;">
<el-col :span="10"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.startTimeFive" field="startTimeFive" placeholder="开启时间" @change="handleEndTimeChange"/></el-form-item></el-col>
<el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.endTimeFive" field="endTimeFive" placeholder="关闭时间" @change="handleEndTimeChange"/></el-form-item></el-col></el-row>
        <div><el-select v-model="form.lightAdjustLevelFive" placeholder="调光等级" class="custom-select move-select" @change="handlelightAdjustLevelFive">
            <el-option label="0%" value="0%"/>
            <el-option label="10%" value="10%"/>
            <el-option label="20%" value="20%"/>
            <el-option label="30%" value="30%"/>
            <el-option label="40%" value="40%"/>
            <el-option label="50%" value="50%"/>
            <el-option label="60%" value="60%"/>
            <el-option label="80%" value="80%"/>
            <el-option label="100%" value="100%"/></el-select></div></el-form>
      <span slot="footer" class="dialog-footer">
<el-button @click="dialogVisibleForStrategy=false">取 消</el-button><el-button type="primary" @click="handleSubmitForStrategy">确 定</el-button></span></el-dialog>
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" label-width="96px">
        <el-form-item label="客户名称" prop="nickName">
          <el-select v-model="selectedUserName" placeholder="请选择客户名称" filterable style="width:100%" @change="handleNicknameChange">
            <el-option v-for="item in options" :key="item.userId" :label="item.nickName" :value="item.userId"/></el-select></el-form-item>
        <el-form-item label="项目名称" prop="projectId">
          <el-select v-model="selectedProjectName" placeholder="请选择项目名称" filterable style="width:100%" @change="handleProjectnameChange">
            <el-option v-for="item in projectnameOptions" :key="item.id" :label="item.projectname" :value="item.id"/></el-select></el-form-item>
        <el-form-item label="灯杆名称" prop="lightName">
          <el-input v-model="form.lightName" placeholder="请输入灯杆名称" /></el-form-item>
        <el-form-item label="灯控类型" prop="provideType">
          <el-select v-model="form.provideType" placeholder="请选择灯控类型" filterable style="width:100%">
            <el-option v-for="dict in dict.type.iot_provide_type" :key="dict.value" :label="dict.label" :value="dict.value"/></el-select></el-form-item>
        <el-form-item label="灯杆序号" prop="boxNo">
          <el-input v-model="form.boxNo" placeholder="请输入灯杆序号" /></el-form-item>
        <el-form-item label="经度" prop="lng">
          <el-input v-model="form.lng" placeholder="请输入经度" @click.native="openMapDialog('lng')" /></el-form-item>
        <el-form-item label="纬度" prop="lat">
          <el-input v-model="form.lat" placeholder="请输入纬度" @click.native="openMapDialog('lat')" /></el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" /></el-form-item>
        <el-form-item label="监控设备编号" prop="ysNoun">
          <el-input v-model="form.ysNoun" placeholder="请输入监控设备编号" /></el-form-item></el-form>
<div slot="footer" class="dialog-footer"><el-button type="primary" @click="submitForm">确 定</el-button><el-button @click="cancel">取 消</el-button></div></el-dialog>
<el-dialog title="选择位置" :visible.sync="mapDialogVisible" width="50%" append-to-body :before-close="handleMapDialogClose" :show-close="false">
<el-autocomplete v-model="searchInput" placeholder="请输入搜索地点" :fetch-suggestions="querySearchAsync" @select="handleSelect" :trigger-on-focus="false" :loading="loading"/>
  <div id="mapContainer" class="map-container" style="height:400px;"/><div slot="footer" class="dialog-footer">
<el-button @click="mapDialogVisible=false">取 消</el-button><el-button type="primary" @click="confirmMapLocation">确 定</el-button></div></el-dialog></div></template>
<script>
import TimePicker from './TimePicker.vue';
import { listHgbox, getHgbox, delHgbox, addHgbox, updateHgbox} from '@/api/iot/hgbox'
import Template from '@/views/iot/template/index.vue'
import row from 'element-ui/packages/row'
import request from '@/utils/request'
import { addCron, listCron, updateCron, updateCronBoxNo } from '@/api/iot/fahgboxcron'
import { listUser } from '@/api/iot/tool'
import { listProject } from '@/api/iot/faproject'
import boxNoList from 'vue-easytable'
import historyUusser from "./historyLog"
import pelectUusser from "./selectLog"
import { loadBMap } from '@/utils/map'
export default {
  dicts: ['iot_provide_type'],
  name: "Hgbox",
  components: { Template,pelectUusser,historyUusser,TimePicker },
  data() {
    return {
      showOperateColumn: false,
      selectedTime: '',
      hours: '',
      minutes: '',
      formattedHour: '00',
      formattedMinute: '00',
      activeField: 'hour',
      hour: 0,
      minute: 0,
      geocoder: null, // 地理编码器
      searchInput: '',
      selectedField: '', // 控制地图弹窗是否显示
      marker: null,
      selectedLocation: {},
      mapDialogVisible: false,
      mapInstance: null,
      selectedProjectId: null,
      selectedUserName: null,
      selectedProjectName: null,
      pollInterval: null, // 轮询定时器
      ssss : '',
      dialogVisibleForStrategy: false, // 控制定时策略对话框的显示状态
      selectedStrategy: '', // 选中的策略数据
      timeRanges: [],
      modified: false,
      deviceSelected: false,
      selectedDevices: 0, // 选中的设备数量
      cronStrategyExists: {},
      brightness:'',
      selectedOption: '',
      dialogVisible: false,
      sldLightLvl: '', // 默认调光等级
      value: ' ', // 默认值
      technology: '',
      selectedRows: [], // 用于存储选中的设备
      selectedProject: '', // 用于存储选中的项目值
      options: [],
      projectnameOptions: [],
      ooptions: ['0%','10%','20%','30%','40%','50%','60%','70%','80%','90%','100%'],
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      total: 0,
      //listCron: [],
      hgboxList: [],
      cronList: [],
      cronBoxNoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerId: null,
        boxNo: null,
        provideType: null,
        lat: null,
        lng: null,
        projectId: null,
        lightName: null,
        ysNoun: null,
        lightAdjustLevel: '',
        city: null,
        status: null,
        state: null,
        weigh: null,
        deleteTime: null,
        lightCurrent: null,
        activePower: null,
        signalt: null,
        mlux: null,
        soundDecibelValue: null,
        pm10: null,
        pm25: null,
        humidity: null,
        temperature: null,
        createTime: null},
      pageSizes: [10,20,30,50], // 可选择的页面大小数组
      // 表单参数
      form: {
        startTime: '00:00',
        endTime: '00:00',
        startTimeTwo: '00:00',
        endTimeTwo: '00:00',
        startTimeThree: '00:00',
        endTimeThree: '00:00',
        startTimeFour: '00:00',
        endTimeFour: '00:00',
        startTimeFive: '00:00',
        endTimeFive: '00:00'},
      // 表单校验
      rules: {boxNo: [{ required: true, message: "灯杆序号不能为空", trigger: "blur" }],}};},
  created() {
    this.getList();
    this.fetchUsers();
    this.fetchProjectnames();
    this.fetchCronBoxNoList();
    this.startPolling(); // 开始轮询
  },
  computed: {row(){return row}},
  beforeDestroy() {
    clearInterval(this.pollInterval);
  },
  methods: {
    handleTableMouseEnter(event) {
      const tableEl = this.$refs.dataTable.$el;
      const rect = tableEl.getBoundingClientRect();
      // 判断鼠标是否在表格右侧100px范围内
      if (event.clientX > rect.right - 100) {
        this.showOperateColumn = true;
      }
    },
    handleTableMouseLeave() {
      this.showOperateColumn = false;
    },
    setMarkerLabel(content) {
      const label = new BMap.Label(content, { offset: new BMap.Size(20, 25) });
      label.setStyle({
        color: "black",
        fontSize: "12px",
        lineHeight: "18px",
        fontFamily: "微软雅黑",
        border: "1px solid #c3c3c3",
        backgroundColor: "#f5f5f5",
        padding: "5px",
        borderRadius: "3px"
      });
      this.marker.setLabel(label);
    },
    // 创建并添加标记
    createMarker(point, icon) {
      if (this.marker) {
        this.mapInstance.removeOverlay(this.marker); // 如果已有标记则移除
      }
      this.marker = new BMap.Marker(point, { icon: icon });
      this.mapInstance.addOverlay(this.marker);
    },
    // 处理地图点击事件
    handleMapClick(e) {
      const point = e.point;
      const { lng, lat } = point;
      // 更新标记和位置
      this.createMarker(point, this.createIcon());
      // 将标记设为可拖动
      this.marker.enableDragging();
      // 更新选中的经纬度
      this.selectedLocation = { lng, lat };
      // 使用地理编码器获取地址信息并设置标签
      if (this.geocoder) {
        this.geocoder.getLocation(point, (result) => {
          if (result && result.address) {
            const labelContent = `地址: ${result.address}<br>经度: ${lng}<br>纬度: ${lat}`;
            this.setMarkerLabel(labelContent);
          }});}
      // 更新表单数据
      this.form.lng = lng;
      this.form.lat = lat;
      // 触发事件，传递经纬度信息给父组件
      this.$emit('mapClickLocation', { lng, lat });
    },
    // 异步搜索位置
    querySearchAsync(queryString, cb = () => {}) {
      if (!queryString) {
        cb([]); // 如果没有查询字符串，调用回调并传递空数组
        return;
      }
      this.loading = true;
      const local = new BMap.LocalSearch(this.mapInstance, {
        onSearchComplete: (results) => {
          this.loading = false;
          const suggestions=results&&results.getNumPois()?[...Array(results.getNumPois())].map((_,i)=>results.getPoi(i)).filter(poi=>poi!==undefined)
              .map(poi => ({
                value: `${poi.title || ''} (${poi.address || ''})`,
                address: poi.address || '',
                point: poi.point
              })):[];
          cb(suggestions); // 调用回调函数并传递结果
          if (suggestions.length > 0) {
            // 处理第一个搜索结果
            this.handleSelect(suggestions[0]);
          }}});
      local.search(queryString); // 开始搜索
    },
    // 关闭地图弹窗时的处理
    handleMapDialogClose() {
      this.selectedLocation = {};
      if (this.marker) {
        this.mapInstance.removeOverlay(this.marker); // 关闭时移除标记
      }
      this.mapInstance.clearOverlays(); // 清除所有覆盖物
    },
    // 创建标记图标
    createIcon() {
      const iconUrl = require('@/assets/bigScreen/img/微信图片_20241209154934-removebg-preview.png');
      const iconSize = new BMap.Size(25, 80); // 设置图标大小
      return new BMap.Icon(iconUrl, iconSize);
    },
    // 处理选择的地址
    handleSelect(item) {
      // 如果已经存在标记，移除旧的标记
      if (this.marker) {
        this.mapInstance.removeOverlay(this.marker); // 移除旧的标记
      }
      // 创建新的标记，并指定使用本地图片作为标记图标
      const newIcon = this.createIcon();  // 创建新的图标
      this.marker = new BMap.Marker(item.point, { icon: newIcon });  // 使用自定义图标的标记
      this.mapInstance.addOverlay(this.marker);  // 将新标记添加到地图中
      // 将地图缩放到选择位置
      this.mapInstance.centerAndZoom(item.point, 12);
      // 更新选中的经纬度
      this.selectedLocation = { lng: item.point.lng, lat: item.point.lat };
      this.form.lng = item.point.lng;
      this.form.lat = item.point.lat;
      // 更新标记的标签内容
      const labelContent = `地址: ${item.address || '未知地址'}<br>经度: ${item.point.lng}<br>纬度: ${item.point.lat}`;
      this.setMarkerLabel(labelContent);  // 设置标记标签
    },
    // 确认选中的位置
    confirmMapLocation() {
      const {lng,lat} = this.selectedLocation;
      if (lng && lat) {
        // 更新表单中的经纬度
        this.form.lng = lng;
        this.form.lat = lat;
        // 传递经纬度给父组件
        this.$emit('confirmMapLocation', this.selectedLocation);
        // 关闭地图弹窗
        this.mapDialogVisible = false;
      } else {
        console.error("error");
      }
    },
    // 打开地图选择对话框
    openMapDialog(field) {
      this.selectedField = field;
      this.mapDialogVisible = true;
      this.searchInput = ''; // 清空搜索框内容
      if (!this.mapInstance) {
        this.getLatLng();
      } else {
        this.querySearchAsync(''); // 开始加载位置
      }
    },
    //地图
    async getLatLng() {
      try {
        const BMap = await loadBMap();
        this.initMap(BMap);
      } catch (error) {
        console.error("Failed to load Baidu Map:", error);
      }
    },
    getMapLocation(BMap) {
      return new Promise((resolve) => {
          //var geolocation = new BMap.Geolocation();
          new BMap.Geolocation().getCurrentPosition(function(r) {
              if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                  //let internalVar = JSON.stringify(r.point);// 这里已经是BMap.Point对象
                  resolve(r.point);
              } else {
                  alert('定位失败: ' + this.getStatus());
              }
          }, {enableHighAccuracy: true});
      });
    },
    // 初始化百度地图
    initMap(BMap) {
      // 创建地图实例
      const self = this;
      this.mapInstance = new BMap.Map("mapContainer");
      const initialPoint = new BMap.Point(119.980343, 31.816579);
      this.getMapLocation(BMap).then(result => {
        console.log(result); // "内部数据"
        this.mapInstance.centerAndZoom(result,18);
        // 初始化标记图标
        const icon = this.createIcon();
        // 创建并添加标记
        this.createMarker(result, icon);
      });
      // 创建地理编码器实例
      this.geocoder = new BMap.Geocoder();
      // 创建MapTypeControl实例，只显示普通地图类型
      const mapTypeControl = new BMap.MapTypeControl({
        mapTypes: [BMAP_NORMAL_MAP] // 只显示二维平面地图
      });
      this.mapInstance.addControl(mapTypeControl);
      this.mapInstance.enableScrollWheelZoom(true);
      // 初始化标记图标
      const icon = this.createIcon();
      // 创建并添加标记
      this.createMarker(initialPoint, icon);
      // 将标记设为可拖动
      this.marker.enableDragging();
      this.marker.addEventListener("dragend", (e) => {
        this.selectedLocation = { lng: e.point.lng, lat: e.point.lat };
      });
      // 添加地图点击事件监听
      this.mapInstance.addEventListener("click", (e) => {
        this.handleMapClick(e);
      });
    },
    handleProvideChange(value) {
      const selectedData = this.projectnameOptions.find(option => option.id === value);
      if (selectedData) {
        console.log('Selected Project ID:', selectedData.id);
        console.log('Selected Project Name:', selectedData.projectname);
        this.selectedProjectId = selectedData.id;
      } else {
        console.error('No matching data found for value:', value);
      }
    },
    handleProjectnameChange(value) {
      const selectedData = this.projectnameOptions.find(option => option.id === value);
      if (selectedData) {
        console.log('Selected Project ID:', selectedData.id);
        console.log('Selected Project Name:', selectedData.projectname);
        this.selectedProjectId = selectedData.id;
      } else {
        console.error('No matching data found for value:', value);
      }
    },
    // 客户名称变化处理
    handleNicknameChange(selectedId) {
      const selectedOption = this.options.find(option => option.userId === selectedId);
      if (selectedOption) {
        console.log(`Selected ID: ${selectedId}, nickName: ${selectedOption.nickName}`);
        this.form.customerId = selectedOption.userId;    // 将选择的 userId 存入 adminId 字段
      }
    },
    // 获取用户列表数据
    async fetchUsers() {
      try {
        const response = await listUser();
        var resList=response.rows;
        if (response && resList) {
          this.options = resList.map(user => ({
            userId: user.userId,
            nickName: user.nickName
          }));
          console.log("options", this.options);
        }
      } catch (error) {
        console.error('error', error);
      }
    },
    //项目名称下拉框
    async fetchProjectnames() {
      try {
        const response = await listProject({});
        var resList=response.rows;
        if (response && Array.isArray(resList)) {
          this.projectnameOptions = resList.map(item => ({
            id: item.id,  // 用于存储的项目 ID
            projectname: item.projectname,  // 用于展示的项目名称
          }));
        } else {
          console.error('Invalid response format:', response);
        }
      } catch (error) {
        console.error('Error fetching project names:', error);
      }
    },
    // 处理开启时间变化，确保下一个策略的开启时间大于当前策略的关闭时间
    handleStartTimeChange(startTime) {
      this.modifiedForm[startTime] = true;
    },
    handleEndTimeChange(field) {
      this.modifiedForm[field] = true;
      console.log('field:', field);
    },
    handlelightStatus() {
      this.modifiedForm.lightStatus = true;
    },
    handlelightAdjustLevel() {
      this.modifiedForm.lightAdjustLevel = true;
    },
    handlelightStatusTwo() {
      this.modifiedForm.lightStatusTwo = true;
    },
    handlelightAdjustLevelTwo() {
      this.modifiedForm.lightAdjustLevelTwo = true;
    },
    handlelightStatusThree() {
      this.modifiedForm.lightStatusThree = true;
    },
    handlelightAdjustLevelThree() {
      this.modifiedForm.lightAdjustLevelThree = true;
    },
    handlelightStatusFour() {
      this.modifiedForm.lightStatusFour = true;
    },
    handlelightAdjustLevelFour() {
      this.modifiedForm.lightAdjustLevelFour = true;
    },
    handlelightStatusFive() {
      this.modifiedForm.lightStatusFive = true;
    },
    handlelightAdjustLevelFive() {
      this.modifiedForm.lightAdjustLevelFive = true;
    },
    handleTimeChange() {
      if (this.hours && this.minutes) {
        this.form.startTime = `${this.hours}:${this.minutes}`;
      } else {
        this.form.startTime = '';
      }
    },
    fetchCronBoxNoList() {
      this.loading = true;
      listCron(this.queryParams).then(response => {
        this.cronList = response.rows;
        this.cronBoxNoList = this.cronList.map(item => item.boxNo);
        console.log('cronBoxNoList:', this.cronBoxNoList);
        this.loading = false;
      }).catch(error => {
        console.error("error:", error);
        this.loading = false;
      });
    },
    fetchHgboxList() {
      this.loading = true;
      listHgbox(this.queryParams).then(response => {
        this.hgboxList = response.rows;
        this.loading = false;
      }).catch(error => {
        console.error("error:", error);
        this.loading = false;
      });
    },
    //定时策略
    openStrategyDialog(row) {
      this.selectedStrategy = row;
      var boxNoo=row.boxNo;
      this.form.boxNo = boxNoo;
      this.form.provideType = row.provideType;
      this.fetchCronDetails(boxNoo);
    },
  // 获取定时任务详情
    fetchCronDetails(boxNo) {
      listCron({ boxNo: boxNo }).then(response => {
          console.log('response:', response);
          console.log('boxNo:', boxNo);
          if (!response || typeof response !== 'object' || !Array.isArray(response.rows)) {
            console.error('response:', response);
            this.$message.error('响应格式不正确');
            return;
          }
          const cron = response.rows[0] || {};
          // 更新表单数据
          this.form = {
            startTime: cron.startTime,
            endTime: cron.endTime,
            boxNo: cron.boxNo,
            provideType: cron.provideType,
            id: cron.id,
            startTimeTwo: cron.startTimeTwo,
            startTimeThree: cron.startTimeThree,
            startTimeFour: cron.startTimeFour,
            startTimeFive: cron.startTimeFive,
            endTimeTwo: cron.endTimeTwo,
            endTimeThree: cron.endTimeThree,
            endTimeFour: cron.endTimeFour,
            endTimeFive: cron.endTimeFive,
            lightStatus: cron.lightStatus,
            lightAdjustLevel : cron.lightAdjustLevel,
            lightStatusTwo: cron.lightStatusTwo,
            lightAdjustLevelTwo : cron.lightAdjustLevelTwo,
            lightStatusThree: cron.lightStatusThree,
            lightAdjustLevelThree : cron.lightAdjustLevelThree,
            lightStatusFour: cron.lightStatusFour,
            lightAdjustLevelFour : cron.lightAdjustLevelFour,
            lightStatusFive: cron.lightStatusFive,
            lightAdjustLevelFive : cron.lightAdjustLevelFive,
          };
          // 清空所有的modified标记
          this.modifiedForm = {
            startTime: false,
            endTime: false,
            startTimeTwo: false,
            endTimeTwo: false,
            startTimeThree: false,
            endTimeThree: false,
            startTimeFour: false,
            endTimeFour: false,
            startTimeFive: false,
            endTimeFive: false,
            lightStatus:false,
            lightAdjustLevel: false,
            lightStatusTwo:false,
            lightAdjustLevelTwo: false,
            lightStatusThree:false,
            lightAdjustLevelThree: false,
            lightStatusFour:false,
            lightAdjustLevelFour: false,
            lightStatusFive:false,
            lightAdjustLevelFive: false,
          };
          // 打印回显的数据
          console.log('form:', this.form);
          // 显示对话框
          this.dialogVisibleForStrategy = true;}).catch(error => {
          console.error('error:', error);this.$message.error('获取定时任务详情失败');});},
    handleSubmitForStrategy() {
      const updatedCronData = [];
      // 确保字段是数字
      const parseValue = (value) => {
        if (typeof value === 'string' && value.includes('%')) {
          // 如果值包含 '%'，去掉 '%' 并转换为数字
          return parseInt(value.replace('%', ''), 10);
        }
        return value;
      };
      console.log('modifiedForm:', this.modifiedForm);
      // 构建更新的数据
      if (this.modifiedForm.startTime) {
        updatedCronData.push({ startTime: this.form.startTime });
      }
      if (this.modifiedForm.endTime) {
        updatedCronData.push({ endTime: this.form.endTime });
      }
      if (this.modifiedForm.startTimeTwo) {
        updatedCronData.push({ startTimeTwo: this.form.startTimeTwo });
      }
      if (this.modifiedForm.endTimeTwo) {
        updatedCronData.push({ endTimeTwo: this.form.endTimeTwo });
      }
      if (this.modifiedForm.startTimeThree) {
        updatedCronData.push({ startTimeThree: this.form.startTimeThree });
      }
      if (this.modifiedForm.endTimeThree) {
        updatedCronData.push({ endTimeThree: this.form.endTimeThree });
      }
      if (this.modifiedForm.startTimeFour) {
        updatedCronData.push({ startTimeFour: this.form.startTimeFour });
      }
      if (this.modifiedForm.endTimeFour) {
        updatedCronData.push({ endTimeFour: this.form.endTimeFour });
      }
      if (this.modifiedForm.startTimeFive) {
        updatedCronData.push({ startTimeFive: this.form.startTimeFive });
      }
      if (this.modifiedForm.endTimeFive) {
        updatedCronData.push({ endTimeFive: this.form.endTimeFive });
      }
      if (this.modifiedForm.lightStatus) {
        updatedCronData.push({ lightStatus: this.form.lightStatus });
      }
      if (this.modifiedForm.lightAdjustLevel) {
        updatedCronData.push({ lightAdjustLevel: parseValue(this.form.lightAdjustLevel) });
      }
      if (this.modifiedForm.lightStatusTwo) {
        updatedCronData.push({ lightStatusTwo: this.form.lightStatusTwo });
      }
      if (this.modifiedForm.lightAdjustLevelTwo) {
        updatedCronData.push({ lightAdjustLevelTwo: parseValue(this.form.lightAdjustLevelTwo) });
      }
      if (this.modifiedForm.lightStatusThree) {
        updatedCronData.push({ lightStatusThree: this.form.lightStatusThree });
      }
      if (this.modifiedForm.lightAdjustLevelThree) {
        updatedCronData.push({ lightAdjustLevelThree: parseValue(this.form.lightAdjustLevelThree) });
      }
      if (this.modifiedForm.lightStatusFour) {
        updatedCronData.push({ lightStatusFour: this.form.lightStatusFour });
      }
      if (this.modifiedForm.lightAdjustLevelFour) {
        updatedCronData.push({ lightAdjustLevelFour: parseValue(this.form.lightAdjustLevelFour) });
      }
      if (this.modifiedForm.lightStatusFive) {
        updatedCronData.push({ lightStatusFive: this.form.lightStatusFive });
      }
      if (this.modifiedForm.lightAdjustLevelFive) {
        updatedCronData.push({ lightAdjustLevelFive: parseValue(this.form.lightAdjustLevelFive) });
      }
      // 更新数据时只发送修改过的字段
      const updatedCron = {
        boxNo: this.form.boxNo,
        provideType: this.form.provideType,
        ...updatedCronData.reduce((acc, curr) => ({ ...acc, ...curr }), {})
      };
      console.log('updatedCron:', updatedCron);
      // 为每个定时任务发送更新请求
      updateCron(updatedCron).then(response => {
          this.$modal.msgSuccess("定时策略更新成功");
          this.dialogVisibleForStrategy = false;
        }).catch(error => {
          console.error('error:', error);
          this.$modal.msgError("操作失败: 请求错误");
        });
    },
    getStateImags(status) {
      return status==='1'?require('@/assets/bigScreen/img/wifion.png'):require('@/assets/bigScreen/img/wifi.png');
    },
    getStatusImage(status) {// 确保比较的是字符串类型
      return status==='1'?require('@/assets/bigScreen/img/light_on.png'):require('@/assets/bigScreen/img/light_off.png');
    },
    getLampErrorImage(status) {// 确保比较的是字符串类型
      return status==='0'?require('@/assets/bigScreen/img/wx1.png'):require('@/assets/bigScreen/img/zc1.png');
    },
    //定时
    openDialog() {
      // 如果没有选择设备，弹出提示
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择设备进行操作。');
        return;
      }
      if (this.selectedRows.length > 1) {
        this.openCronDialog();
        return;
      }
      const selectedBoxNo = this.selectedRows[0].boxNo;
      this.checkDeviceHasCron(selectedBoxNo).then(exists => {
        if (exists) {
          this.$message.warning('已选择设备存在定时任务，请修改已有定时任务。');
        } else {
          this.openCronDialog();  // 设备没有定时任务，允许打开对话框
        }
      }).catch(error => {
        this.$message.error('检查设备时出错: ' + error.message);
      });
    },
    openCronDialog() {
      // 清空表单数据
      this.form = {
        startTime: '',
        endTime: '',
        startTimeTwo: '',
        endTimeTwo: '',
        startTimeThree: '',
        endTimeThree: '',
        startTimeFour: '',
        endTimeFour: '',
        startTimeFive: '',
        endTimeFive: '',
        lightStatus: '',
        lightAdjustLevel: '',
        lightStatusTwo: '',
        lightAdjustLevelTwo: '',
        lightStatusThree: '',
        lightAdjustLevelThree: '',
        lightStatusFour: '',
        lightAdjustLevelFour: '',
        lightStatusFive: '',
        lightAdjustLevelFive: '',
      };
      this.dialogVisible = true;
    },
    checkDeviceHasCron(boxNo) {
      return new Promise((resolve, reject) => {
        listCron({ boxNo }).then(response => {
            resolve(!!response.rows.length);
          }).catch(error => {
            reject(error);
          });
      });
    },
    handleSubmitForStrategys() {
      // 如果没有选择设备，弹出提示
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择设备');
        return;
      }
      // 获取选中的设备的provideType
      const provideTypes = this.selectedRows.map(row => row.provideType);
      // 获取选中的设备的boxNo
      const selectedBoxNos = new Set(this.selectedRows.map(row => row.boxNo));
      console.log('selectedBoxNos:', selectedBoxNos);
      console.log('provideTypes:', provideTypes);
      // 获取表单中的定时策略数据
      const cronData = {
        startTime: this.form.startTime,
        endTime: this.form.endTime,
        startTimeTwo: this.form.startTimeTwo,
        endTimeTwo: this.form.endTimeTwo,
        startTimeThree: this.form.startTimeThree,
        endTimeThree: this.form.endTimeThree,
        startTimeFour: this.form.startTimeFour,
        endTimeFour: this.form.endTimeFour,
        startTimeFive: this.form.startTimeFive,
        endTimeFive: this.form.endTimeFive,
        lightStatus: this.form.lightStatus,
        lightAdjustLevel: this.parseToNumber(this.form.lightAdjustLevel),
        lightStatusTwo: this.form.lightStatusTwo,
        lightAdjustLevelTwo: this.parseToNumber(this.form.lightAdjustLevelTwo),
        lightStatusThree: this.form.lightStatusThree,
        lightAdjustLevelThree: this.parseToNumber(this.form.lightAdjustLevelThree),
        lightStatusFour: this.form.lightStatusFour,
        lightAdjustLevelFour: this.parseToNumber(this.form.lightAdjustLevelFour),
        lightStatusFive: this.form.lightStatusFive,
        lightAdjustLevelFive: this.parseToNumber(this.form.lightAdjustLevelFive),
      };
      console.log('cronData:', cronData);
      // 定义定时策略数组，仅包含选中的策略和对应的开关灯及调光数据
      const strategies = [
        { start: cronData.startTime, end: cronData.endTime, lightStatus: cronData.lightStatus, lightAdjustLevel: cronData.lightAdjustLevel },
        { start: cronData.startTimeTwo, end: cronData.endTimeTwo, lightStatusTwo: cronData.lightStatusTwo, lightAdjustLevelTwo: cronData.lightAdjustLevelTwo },
        { start: cronData.startTimeThree, end: cronData.endTimeThree, lightStatusThree: cronData.lightStatusThree, lightAdjustLevelThree: cronData.lightAdjustLevelThree },
        { start: cronData.startTimeFour, end: cronData.endTimeFour, lightStatusFour: cronData.lightStatusFour, lightAdjustFour: cronData.lightAdjustLevelFour },
        { start: cronData.startTimeFive, end: cronData.endTimeFive, lightStatusFive: cronData.lightStatusFive, lightAdjustFive: cronData.lightAdjustLevelFive },];
      // 确保至少填写一个定时策略
      if (!strategies.some(strategy => strategy.start && strategy.end)) {
        this.$message.warning('请至少填写一个定时策略');
        return;
      }
      // 准备检查和添加/更新定时策略的Promise数组
      const checkPromises = [...selectedBoxNos].map(boxNo => this.checkDeviceHasCron(boxNo));
      // 等待所有检查完成后处理结果
      Promise.all(checkPromises).then(results => {
          // 遍历每个结果，处理对应的boxNo
          results.forEach((deviceExists, index) => {
            const boxNo = [...selectedBoxNos][index];
            const provideType = [...provideTypes][index];
            if (!deviceExists) {
              // 如果设备没有定时策略，则添加定时策略
              this.addDeviceAndCron(boxNo, provideType, cronData);
            } else {
              // 如果设备已有定时策略，则更新定时策略
              this.updateCronFields(boxNo, provideType, cronData);
            }
          })
          // 如果有任何操作，统一提示成功
          if (results.some(result => result)) {
            this.$message.success('定时策略操作成功');
          }
        }).catch(error => {
          // 如果检查设备时出错，弹出错误提示
          this.$message.error('检查设备时出错: ' + error.message);
        });
    },
    // 解析百分比并转换为数字类型，如果是百分比格式，去除百分号并转换为数字；否则直接返回数值或字符串本身
    parseToNumber(value) {
      if (typeof value === 'string' && value.includes('%')) {
        // 如果是百分比格式，去除百分号并转换为数字
        return parseFloat(value.replace('%', ''));
      } else if (typeof value === 'number') {
        // 如果是其他数字类型，直接返回数值
        return value;
      } else {
        // 如果是其他格式，直接返回原值
        return value;
    }},
    addDeviceAndCron(boxNo, provideType, cronData) {
      // 为设备添加定时策略，并处理错误
      addCron({boxNo,provideType,...cronData}).then(() => {
          // 更新前端数据，不必重新请求列表
          this.cronBoxNoList.push(boxNo);
          this.cronList.push({ boxNo, ...cronData });
          // 直接在这里显示成功提示
          this.$message.success('定时任务添加成功');
          this.dialogVisible = false;
          this.getList();}).catch(error => {
          // 如果添加失败且错误码为DUPLICATE_BOXNO，尝试更新定时策略
          if (error.code === 'DUPLICATE_BOXNO') {
            this.updateCronFields(boxNo, provideType, cronData);
          } else {
            // 其他错误弹出失败提示
            this.$message.error('添加设备失败: ' + error.message);
          }
    });},
    updateCronFields(boxNo, provideType, cronData) {
      // 更新设备的定时策略字段，并处理错误
      updateCron({ boxNo, provideType, ...cronData }).then(() => {
          // 更新前端数据
          const index = this.cronList.findIndex(item => item.boxNo === boxNo);
          if (index !== -1) {
            // 找到对应的定时策略并更新
            this.cronList[index] = { boxNo, ...cronData };
          }
          this.dialogVisible = false;
          this.getList();
        }).catch(error => {
          // 更新定时策略失败时弹出错误提示
          this.$message.error('更新定时策略失败: ' + error.message);
        });
    },
    // 处理开灯事件
    handleTurnOn() {
      const selectedRows = this.selectedRows;
      if (selectedRows.length === 0) {
        this.$message.warning('请选择设备进行操作。');
        return;
      }
      const requests = selectedRows.map(row => {
        if (!row.boxNo) {
          this.$message.error('选中的设备缺少设备编号');
          return null;
        }
        return this.publish({
          lightLevel: 100,
          type: 0,
          id: row.id,
          provideType: row.provideType,
          sno: row.boxNo,
          productKey: "a1vJ7tC7nM0",
          thingData: {
            params: {
              lightStatus: 1,
              lightAdjustLevel: 100
            }
          }
        });
      }).filter(request => request !== null);
      console.log('return:', requests);
      Promise.all(requests).then(results => {
          console.log('returns:', results); // 输出: ['result1', 'result2', 'result3']
          let msgsuccess="";
          let msgfail="";
          let jsonArray = [];
          results.forEach(item=>{
            console.log('index:', item.data);
            jsonArray.push(item.data);
          });
          console.log('jsonArray:', jsonArray);
          const result = jsonArray.reduce((acc, obj) => {
            return { ...acc, ...obj };
          }, {});
          console.log('result:', result);
          // 遍历键值对
          for (const [key, value] of Object.entries(result)) {
              console.log(key, value);
              if(value){
                msgsuccess+=key+",";
              }else{
                msgfail+=key+",";
              }
          }
          console.log('msgslength:', msgsuccess.length);
          console.log('msgflength:', msgfail.length);
          console.log('msgsuccess:', msgsuccess);
          console.log('msgfail:', msgfail);
          const msgsuccrslt = msgsuccess.substring(0,msgsuccess.length-1);
          const msgfailrslt = msgfail.substring(0,msgfail.length-1);
          if(msgsuccess.length>0&&msgfail.length>0){
            this.$message.warning('开灯成功的灯杆序号：'+msgsuccrslt+' 开灯失败的灯杆序号：'+msgfailrslt,{duration:15000});
          }
          if(msgsuccess.length>0&&msgfail.length==0){
            this.$modal.msgSuccess('开灯成功的灯杆序号：'+msgsuccrslt,{duration:18000});
          }
          if(msgsuccess.length==0&&msgfail.length>0){
            this.$message.warning('开灯失败的灯杆序号：'+msgfailrslt,{duration:15000});
          }
          this.getList();
      }).catch(error => {
          console.error(error);
      });},
    handleTurnOff() {
      const selectedRows = this.selectedRows;
      if (selectedRows.length === 0) {
        this.$message.warning('请选择设备进行操作。');
        return;
      }
      const requests = selectedRows.map(row => {
        if (!row.boxNo) {
          this.$message.error('选中的设备缺少设备编号');
          return null;
        }
        return this.publish({
          lightLevel: 0,
          type: 1,
          id: row.id,
          provideType: row.provideType,
          sno: row.boxNo,
          productKey: "a1vJ7tC7nM0",
          thingData: {
            params: {
              lightStatus: 0
            }
          }
        });
      }).filter(request => request !== null);
      console.log('return:', requests);
      Promise.all(requests).then(results => {
          console.log('returns:', results); // 输出: ['result1', 'result2', 'result3']
          let msgsuccess="";
          let msgfail="";
          let jsonArray = [];
          results.forEach(item=>{
            console.log('index:', item.data);
            jsonArray.push(item.data);
          });
          console.log('jsonArray:', jsonArray);
          const result = jsonArray.reduce((acc, obj) => {return { ...acc, ...obj };},{});
          console.log('result:', result);
          // 遍历键值对
          for (const [key, value] of Object.entries(result)) {
              console.log(key, value);
              if(value){
                msgsuccess+=key+",";
              }else{
                msgfail+=key+",";
              }
          }
          console.log('msgslength:', msgsuccess.length);
          console.log('msgflength:', msgfail.length);
          console.log('msgsuccess:', msgsuccess);
          console.log('msgfail:', msgfail);
          const msgsuccrslt = msgsuccess.substring(0,msgsuccess.length-1);
          const msgfailrslt = msgfail.substring(0,msgfail.length-1);
          if(msgsuccess.length>0&&msgfail.length>0){
            this.$message.warning('关灯成功的灯杆序号：'+msgsuccrslt+' 关灯失败的灯杆序号：'+msgfailrslt,{duration:15000});
          }
          if(msgsuccess.length>0&&msgfail.length==0){
            this.$modal.msgSuccess('关灯成功的灯杆序号：'+msgsuccrslt,{duration:18000});
          }
          if(msgsuccess.length==0&&msgfail.length>0){
            this.$message.warning('关灯失败的灯杆序号：'+msgfailrslt,{duration:15000});
          }
          this.getList();
      }).catch(error => {
          console.error(error);
      });},
    publish(snThing) {
      console.log('1:', JSON.stringify(snThing));
      return request({
        url: '/mqtt/backclient/publish',
        method: 'post',
        data: snThing,
        headers: {
          'Content-Type': 'application/json'
        }
      })
    },
    updateDeviceStatus(selectedRows, successMessage) {
      const promises = selectedRows.map(row => updateHgbox(row));
      Promise.all(promises).then(() => {
          this.$message.success(successMessage, { duration: 2000 });
          this.getList(); // 重新获取设备列表
        }).catch(error => {
          console.error("error:", error);
          this.$message.error("更新设备状态失败");
        });
    },
    formatDate(timestamp) {
      const date = new Date(timestamp * 1000);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;},
    getList() {
      this.loading = true;
      listHgbox(this.queryParams).then(response => {
          this.hgboxList = response.rows.map(row => ({...row,
            adminNickname: this.getNicknameById(row.customerId),  // 映射 adminId 和 nickName
          }));
          this.total = response.total;
          this.loading = false;
        }).catch(error => {
          console.error("error:", error);
          this.loading = false;
        });
    },
    getNicknameById(adminId) {
      var optionss=this.options;
      if (Array.isArray(optionss)) {
        const option = optionss.find(option => option.userId === adminId);
        return option ? option.nickName : '';  // 如果找到对应选项则返回 nickName，否则返回空字符串
      }
      return '';
    },
    startPolling() {// 每10分钟秒轮询一次数据
      this.pollInterval = setInterval(this.getList, 600000);},
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        customerId: null,
        provideType: null,
        boxNo: null,
        lat: null,
        lng: null,
        remark: null,
        projectId: null,
        lightName: null,
        ysNoun: null,
        city: null,
        status: null,
        state: null,
        weigh: null,
        deleteTime: null,
        lightVolt: null,
        lightCurrent: null,
        activePower: null,
        signalt: null,
        mlux: null,
        soundDecibelValue: null,
        pm10: null,
        pm25: null,
        humidity: null,
        temperature: null,
        createTime: null,
        lightStatus: null,
        lightAdjustLevel: null,
        startTime: null,
        endTime: null,
        startTimeTwo: null,
        endTimeTwo: null,
        startTimeThree: null,
        endTimeThree: null,
        startTimeFour: null,
        endTimeFour: null,
        startTimeFive: null,
        endTimeFive: null,
        lightStatusTwo: null,
        lightAdjustLevelTwo: null,
        lightStatusThree: null,
        lightAdjustLevelThree: null,
        lightStatusFour: null,
        lightAdjustLevelFour: null,
        lightStatusFive: null,
        lightAdjustLevelFive: null
      };
      this.resetForm("form");
      this.selectedProjectId = '';
      this.selectedUserName = '';
      this.selectedProjectName = '';
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = selection.length === 0;
      this.selectedRows = selection;
      this.hgboxList.forEach(device => {
        device.checked = selection.some(item => item.id === device.id);
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增";
    },
    operateUp(row) {
      this.reset();
      this.$refs.select.show(row.boxNo);
    },
    historyUpd(row) {
      this.reset();
      this.$refs.history.show(row.boxNo);
    },
    handleUpdate(row) {
      this.reset(); // 重置表单
      const id = row.id || this.ids;
      getHgbox(id).then(response => {
        let dataa = response.data;
        this.form = dataa;
        this.selectedUserName = dataa.sysUser?dataa.sysUser.nickName:null;
        this.selectedProjectId = dataa.projectId;
        this.selectedProjectName = dataa.faProject?dataa.faProject.projectname:null;
        this.ssss = dataa.boxNo;
        this.open = true;
        this.title = "修改";});
    },
    updtLevel() {
      const newLightLevel = parseInt(this.sldLightLvl); // 将选中的调光等级转换为数字
      // 更新所有被勾选设备的调光等级
      this.hgboxList.forEach(device => {
        if (device.checked) {
          // 创建 SnThing 对象并发送到后端
          const snThing = {
            lightLevel: newLightLevel,
            type: 2,
            id: device.id,
            provideType: device.provideType,
            sno: device.boxNo, // 使用设备对象的 boxNo 属性
            productKey: "a1vJ7tC7nM0", // 确保这是正确的 productKey
            thingData: {
              params: {
                lightAdjustLevel: newLightLevel // 设置调光等级
              }
            }
          };
          // 调用 publish 方法发送数据到后端
          this.publish(snThing).then(response => {
            this.$modal.msgSuccess("调光成功");
            this.getList();
            this.sldLightLvl='';
          }).catch(error => {
            console.error('error', error);
            this.$modal.msgError("调光失败");
          });
        }
      });
    },
    submitForm() {
      // 手动验证表单
      if (!this.form.customerId) {this.$message.error('客户名称不能为空');return;}
      if (!this.selectedProjectId) {this.$message.error('项目名称不能为空');return;}
      if (!this.form.provideType) {this.$message.error('灯控类型不能为空');return;}
      if (!this.form.boxNo) {this.$message.error('灯控序号不能为空');return;}
      const dataToSubmit={lightName:this.form.lightName,remark:this.form.remark,provideType:this.form.provideType,boxNo:this.form.boxNo,customerId:this.form.customerId,
        projectId:this.selectedProjectId,lng:this.form.lng,lat:this.form.lat,ysNoun:this.form.ysNoun};
      this.form.lightAdjustLevel = String(this.form.lightAdjustLevel);
      this.$refs["form"].validate(valid => {
        if (valid) {
          const lightAdjustLevel = this.form.lightAdjustLevel;
          if (typeof lightAdjustLevel === 'string') {
            this.form.lightAdjustLevel = parseInt(lightAdjustLevel.replace('%', ''));
          } else {
            console.error("lightAdjustLevel", lightAdjustLevel);
            this.$modal.msgError("lightAdjustLevel必须是字符串");
            return;}
          const currentTimestamp = Math.floor(Date.now() / 1000);
          if (!this.form.id) {// 新增操作
            addHgbox({ ...dataToSubmit,createTime:this.formatDate(currentTimestamp) }).then(response => {
              console.log('response:', response)
              if(response != undefined){
                this.$modal.msgSuccess("新增成功");
              }
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error("error", error);
              this.$modal.msgError("新增失败");
            });
          } else {// 修改操作
            //this.form.updateTime = this.formatDate(currentTimestamp); // 更新修改时间
            updateHgbox({ ...dataToSubmit,id:this.form.id,updateTime:this.formatDate(currentTimestamp) }).then(response => {
              console.log('response:', response)
              if(response != undefined){
                this.$modal.msgSuccess("修改成功");
              }
              this.open = false;
              this.getList();
              this.fetchCronBoxNoList();
            }).catch(error => {
              console.error("error", error);
              this.$modal.msgError("修改失败");});}
          let b;
          listCron({ boxNo: this.ssss }).then(response => {// 检查 response.rows 是否存在并且不是空数组
              if (response.rows && response.rows.length > 0) {
                b = response.rows[0].id;
                const cronData = {id:b,boxNo:this.form.boxNo};
                updateCronBoxNo(cronData).then(response => {// 更新成功
                }).catch(error => {
                  console.error("error", error);
                  this.$modal.msgError("定时任务更新失败");});}
            }).catch(error => {
              this.$modal.msgError("获取定时任务列表失败");
            });
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除').then(function() {
        return delHgbox(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('iot/hgbox/export', {
        ...this.queryParams
      }, `hgbox_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.hover-operate-table {
  position: relative;
  .el-table__body-wrapper {
    overflow-x: auto !important;
    scrollbar-width: thin;
    scrollbar-color: #c1c1c1 #f5f5f5;
    &::-webkit-scrollbar {
      height: 8px;
      background-color: #f5f5f5;
    }
    &::-webkit-scrollbar-thumb {
      background-color: #c1c1c1;
      border-radius: 4px;
    }
  }
}
.el-table .operate-column {
  position: sticky;
  right: 0;
  opacity: 0;
  transition: opacity 0.3s;
  pointer-events: none;
  background-color: #fff;
  z-index: 2; /* 确保在滚动时显示在其他内容上方 */
}
.el-table .operate-column.show {
  opacity: 1;
  pointer-events: auto;
}
.el-table .operate-column .cell {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
  box-shadow: -2px 0 4px rgba(0, 0, 0, 0.1); /* 添加阴影增强视觉效果 */
}
.el-table__body tr td {
  position: relative;
}
.combined-time-select .el-select-dropdown__list {
  padding: 0;
  display: flex;
}
.time-selector-container {
  display: flex;
  align-items: center;
  padding: 10px;
}
.time-section {
  display: flex;
  flex-direction: column;
}
.time-label {
  text-align: center;
  padding: 5px 0;
  color: #909399;
  font-size: 12px;
}
.time-options {
  max-height: 200px;
  overflow-y: auto;
}
.time-separator {
  padding: 0 5px;
  font-size: 16px;
  align-self: flex-end;
  margin-bottom: 25px;
}
.time-prefix {
  color: #606266;
}
.time-option {
  padding: 0 10px;
  text-align: center;
}
.vue-clock-picker {
  height: 20% !important;
  width: 30% !important;
}
.custom-clock-picker {
  display: flex;
  align-items: center;
  font-family: Arial, sans-serif;
}
.time-display {
  display: flex;
  align-items: center;
  margin-right: 5px;
  font-size: 16px;
}
.time-part {
  border: none;
  background: transparent;
  width: 20px;
  text-align: center;
  font-size: inherit;
  font-family: inherit;
  color: inherit;
  padding: 0;
  outline: none;
}
.time-part:focus {
  border-bottom: 1px solid #409EFF; /* Element UI primary color */
}
.colon {
  margin: 0 2px;
}
.arrow-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.arrow-up, .arrow-down {
  cursor: pointer;
  font-size: 12px;
  color: #606266;
  user-select: none;
  padding: 2px 5px;
  line-height: 1;
}
.arrow-up:hover, .arrow-down:hover {
  color: #409EFF;
}
.small-padding .cell {
  display: flex; /* 使用flex布局 */
  justify-content: center; /* 水平居中 */
}
.custom-select .el-input__inner {
  border-color: #093077; /* 设置边框颜色为蓝色 */
  border-style: solid; /* 确保边框是实线 */
}
.custom-select {
  width: 20%;
  margin-top: 10px;
  margin-left: 60px;
}
.move-select {
  position: relative;
  top: -24px;
}
</style>
